import { defineStore } from 'pinia'
import { loginUser, getCurrentUser } from '@/services/authService'

export const useAuthStore = defineStore('auth', {
  state: () => ({
    user: null,
    token: null,
    isAuthenticated: false
  }),

  actions: {
    async login(credentials) {
      try {
        const response = await loginUser(credentials)
        this.user = response.user
        this.token = response.token
        this.isAuthenticated = true
      } catch (error) {
        this.logout()
        throw error
      }
    },

    async checkAuth() {
      try {
        const user = await getCurrentUser()
        if (user) {
          this.user = user
          this.isAuthenticated = true
        } else {
          this.logout()
        }
      } catch (error) {
        this.logout()
        throw error
      }
    },

    logout() {
      this.user = null
      this.token = null
      this.isAuthenticated = false
      localStorage.removeItem('token')
    }
  }
})
